package UDP;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class userSever {
    DatagramSocket socket = null;
    private String ServerIp;
    private int ServerPort;

    public userSever(String ip, int port) {
        ServerIp = ip;
        ServerPort = port;
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }

    public void start() throws IOException {
        while(true) {
            System.out.println("输入请求");
            Scanner in = new Scanner(System.in);
            //发起的请求
            String request = in.nextLine();
            //包装请求
            DatagramPacket req = new DatagramPacket(request.getBytes(), request.length(),
                    InetAddress.getByName(ServerIp), ServerPort);
            //发送请求
            socket.send(req);
            //接受返回
            DatagramPacket responseP = new DatagramPacket(new byte[2048], 2048);
            socket.receive(responseP);
            //打印请求
            String response = new String(responseP.getData(), 0, responseP.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        userSever u = new userSever("127.0.0.1", 8888);
        u.start();
    }
}




















